//
//  MessageViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/2.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Common.h"
#import <MJRefresh.h>
#import "AppDelegate.h"
#import "JlUserManager.h"
#import "VRGCalendarView.h"
#import "UWDatePickerView.h"
#import "LoginViewController.h"
#import "MessageCell.h"
#import "MessageViewController.h"
#import "MessageMapViewController.h"
#import "CLUIBaseViewController+Empty.h"


#define TabbarItemNums 5.f
#define CellHeight 51
static NSString *cellIdentifier = @"MessageCell";

typedef NS_ENUM(NSInteger, SelectBtnStatus) {
    SelectBtnStatusDefualt = 0, //默认为未选中状态
    SelectBtnStatusSelect ,     //选中状态

};

@interface MessageViewController() <UITableViewDelegate,VRGCalendarViewDelegate,UITableViewDataSource> {
    NSDateFormatter *dateFormatter;
}
@property (strong, nonatomic) UIButton *selectBtn;
@property (assign, nonatomic) SelectBtnStatus selectBtnStatus;
@property (strong, nonatomic) UIView *maskView;
@property (strong, nonatomic) NSMutableArray *showDataSouce;
@property (strong, nonatomic) NSMutableArray *showDataType;
@property (strong, nonatomic) DropDownView *dropView;
@property (strong, nonatomic) VRGCalendarView *pickerView;
@property (strong, nonatomic) id responseObject;
@property (strong, nonatomic) NSString *queryDate;
@property (assign, nonatomic) int degreeType;
@property (assign, nonatomic) NSInteger index;


@end

@implementation MessageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"健康预警";
    self.degreeType = 0;
    self.queryDate = @"0";
    self.showDataSouce = [NSMutableArray array];
    [self setNavBarLeftAndRightItem];
     [self showNavgationWithLeftItemWithTitle:@"首页"];
    [self initTableView];
    [self requestEarlyWarning];
    [self requestEarlyWarningType];
}

#pragma mark - 数据请求
- (void)requestEarlyWarning{
    [SVProgressHUD showWithStatus:@"预警信息.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[NSNumber numberWithInt:14] forKey:@"limit_count"];
    [dict setObject:[NSNumber numberWithInt:self.degreeType] forKey:@"degree_type"];
    [dict setObject:self.queryDate forKey:@"query_date"];
    [dict setObject:[NSNumber numberWithInteger:self.index] forKey:@"start_index"];
    WS(weakSelf);
    [[BaseDataRequest alloc] getEarlyWarningData:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self clearLabelEmptyCate];
        [self.tableView.footer endRefreshing];
        [self.tableView.footer setTitle:@"" forState:MJRefreshFooterStateIdle];
        if ([status isEqualToString:@"0"]) {
            self.responseObject = responseObject;
            NSMutableArray *arrResult = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"result"]];
            if (arrResult.count == 0 || arrResult.count < 14) {
                [self.tableView.footer noticeNoMoreData];
            }
            [self.showDataSouce addObjectsFromArray:arrResult];
            if(self.showDataSouce.count == 0){
                [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"这里还没有内容" withImage:[UIImage imageNamed:@"icon_ blank"]];
                self.tableView.footer.hidden = YES;
            }
            [self.tableView reloadData];
        }else{
            [self clearLabelEmptyCate];
            if (self.tableView.footer.isRefreshing) {
                self.index--;
            }
            if(self.showDataSouce.count == 0){
                self.tableView.footer.hidden = YES;
                [weakSelf showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"出错了，稍后再试吧" withImage:[UIImage imageNamed:@"icon_wifi"]];
                self.tableView.footer.hidden = YES;
            }else{
                if (error != nil) {
                    TIPSFORVIEW(@"请检测网络设置");
                }else{
                    TIPSFORVIEW([responseObject objectForKey:@"message"]);
                }
            }
        }
    }];
}

- (void)requestEarlyWarningType{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc] requestEarlyWarningType:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        if ([status isEqualToString:@"0"]) {
            _showDataType = [NSMutableArray arrayWithArray:[responseObject objectForKey:@"result"]];
        }
    }];
}

#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _showDataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    NSMutableDictionary *model = [_showDataSouce objectAtIndex:indexPath.row];
    cell.messageName.text = [model objectForKey:@"warn_type"];
    NSString *time = [model objectForKey:@"warn_date"];
    NSLog(@"%@\n",time);
    [cell.messageImage sd_setImageWithURL:[NSURL URLWithString:[model objectForKey:@"type_url"]] placeholderImage:nil];
    cell.messageTime.text = [self timeStamp:time];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectBtn.selected) {
        _dropView.hidden = YES;
        self.selectBtn.selected = NO;
        self.selectBtnStatus = SelectBtnStatusDefualt;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *model = [_showDataSouce objectAtIndex:indexPath.row];
    NSString *time = [model objectForKey:@"warn_date"];
    NSString *type = [model objectForKey:@"warn_type"];
    MessageMapViewController *messageMap = [[MessageMapViewController alloc] initWithNibName:@"MessageMapViewController" bundle:nil];
    messageMap.warningID = [model objectForKey:@"warn_id"];
    messageMap.time = [self timeStamp:time];
    messageMap.heading = type;
    [self.navigationController pushViewController:messageMap animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _dropView.hidden = YES;
    self.selectBtn.selected = NO;
    self.selectBtnStatus = SelectBtnStatusDefualt;
}


#pragma mark - VRGCalendarView Delegate
-(void)calendarView:(VRGCalendarView *)calendarView
    switchedToMonth:(int)month
       targetHeight:(float)targetHeight
           animated:(BOOL)animated {
}

-(void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date {
    self.queryDate = [dateFormatter stringFromDate:date];
    self.degreeType = 0;
    self.index = 0;
    [self.showDataSouce removeAllObjects];
    [self hiddenPickerView];
    [self requestEarlyWarning];
}

#pragma mark - 私有方法
- (void)setNavBarLeftAndRightItem{
    [self showNavBarWithRightOneImage:[UIImage imageNamed:@"dateBtn"]
                     andRightTwoImage:[UIImage imageNamed:@"arr_up"]
               andRightTwoSelectImage:[UIImage imageNamed:@"arr_down"]
                    andRightOneAction:@selector(dateAction)
                     andRighTwoAction:@selector(selectAction:)];
}

- (void)initTableView{
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        if (_showDataSouce.count == 0) {
            _index = 0;
        }else{
            _index ++;
        }
        [weakSelf requestEarlyWarning];
    }];
}

//日期选择
- (void)dateAction{
    [self setupDateView:DateTypeOfStart];
}

- (void)setupDateView:(DateType)type {
    if (self.selectBtnStatus == SelectBtnStatusSelect) {
        [self selectAction:self.selectBtn];
    }
    if (_pickerView == nil) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenPickerView)]];
        _maskView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        [self.view addSubview:_maskView];
        _maskView.tag = 0x22;
        _pickerView = [[VRGCalendarView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)/2 - kVRGCalendarViewWidth/2, CGRectGetHeight(self.view.frame)/2 - 271 / 2, kVRGCalendarViewWidth, 0)];
        _pickerView.delegate = self;
        [self.view addSubview:_pickerView];
    } else {
        [self hiddenPickerView];
        [self.view addSubview:_pickerView];
    }
}

- (void)hiddenPickerView {
    _maskView.hidden = _pickerView.hidden= !_pickerView.hidden;
}

//警报选择
- (void)selectAction:(id)sender {
    if (_maskView != nil && _pickerView.hidden == NO) {
       _maskView.hidden = _pickerView.hidden = YES;
    }
    self.selectBtn = (UIButton *)sender;
    if (_dropView == nil) {
        _dropView = [[DropDownView alloc] initWithFrame:CGRectMake(KScreenWidth - 110, 2, 100, _showDataType.count*32)];
        _dropView.dataSource = _showDataType;
        [self.view addSubview:_dropView];
        WS(weakSelf);
        _dropView.action = ^(NSInteger index, NSString *type){
            weakSelf.tableView.footer.hidden = NO;
            [weakSelf.tableView.footer resetNoMoreData];
            weakSelf.queryDate = @"0";
            weakSelf.degreeType = [type intValue];
            weakSelf.index = 0;
            [weakSelf.showDataSouce removeAllObjects];
            [weakSelf requestEarlyWarning];
            [weakSelf selectAction:weakSelf.selectBtn];
        };
        self.selectBtn.selected = YES;
        self.selectBtnStatus = SelectBtnStatusSelect;
    }else{
        _dropView.hidden = !_dropView.hidden;
        self.selectBtn.selected = !self.selectBtn.selected;
        if (_dropView.hidden) {
            self.selectBtnStatus = SelectBtnStatusDefualt;
        }else{
            self.selectBtnStatus = SelectBtnStatusSelect;
        }
    }
}

- (NSString *)timeStamp:(NSString *)strTime{
    NSDateFormatter *dateFormatte = [[NSDateFormatter alloc] init];
    [dateFormatte setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeInterval time=[strTime doubleValue];
    NSDate*detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    NSString*currentDateStr = [dateFormatte stringFromDate:detaildate];
    return currentDateStr;
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
